<?php
namespace App\Admin\Controllers\Stocking;

use App\Importer\Stocking\Sku\SkuImporter;
use App\Models\Basics\SysArea;
use App\Models\Product\ProductSku;
use App\Models\Stocking\StockingSkuOther;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Facades\DB;
class SkuOtherUploadController extends AdminController{

    protected $title = '上传文件';

    protected function grid()
    {
        return view("stocking.other.upload.index");
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $re = $this->_importFile($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importFile(UploadedFile $file){
        try{
            $data = Excel::toArray(new SkuImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            DB::beginTransaction();
            $errors = [];
            $count = 1;
            $arr = [];
            $userId = Admin::user()->id;
            foreach($data as $row){
                $count++;
                $_area = $row[0] ? trim($row[0]) : '';
                $sku = $row[1] ? trim($row[1]) : '';
                $applyNum = $row[2] ? trim($row[2]) : 0;
                $applyRemark = $row[3] ? trim($row[3]) : null;
                $applyUser = $row[4] ? trim($row[4]) : '';
                if(!$_area || !$sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $area = strtoupper($_area);
                $key = $area.'_'.$sku;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                if(!is_numeric($applyNum)){
                    $errors[$count] = '备货数量格式有误';
                    continue;
                }
                if($applyNum <= 0){
                    $errors[$count] = '备货数量需大于0';
                    continue;
                }
                $areaId = SysArea::getSysAreaIdByArea($area);
                if(!$areaId){
                    $errors[$count] = $_area.'系统不存在';
                    continue;
                }
                $pSkuId = ProductSku::getValueByCode($sku,'id');
                if(!$pSkuId){
                    $errors[$count] = $sku.'系统不存在';
                    continue;
                }
                if($applyUser){
                    $sellerId = User::getIdByUsername($applyUser);
                    if(!$sellerId){
                        $errors[$count] = $applyUser.'不存在或已停用';
                        continue;
                    }
                }else{
                    $sellerId = $userId;
                }
                $reCount = StockingSkuOther::query()
                    ->where('area_id',$areaId)
                    ->where('psku_id',$pSkuId)
                    ->where('status',1)
                    ->count();
                if($reCount > 0){
                    $errors[$count] = $key.'审批中勿修改';
                    continue;
                }
                StockingSkuOther::query()->create(
                    [
                        'area_id' => $areaId,
                        'psku_id' => $pSkuId,
                        'seller_id' => $sellerId,
                        'apply_num' => $applyNum,
                        'approval_num' => $applyNum,
                        'remark' => $applyRemark,
                    ]
                );
            }
            DB::commit();
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
